package fi.profecons.csswindows;

import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import fi.profecons.csswindows.toolkit.FileUpload;

class State{

	private List elements;

	private Vector script;

	private boolean scripting;
	
	private URL url;
	
	private FileUpload fileUpload;
	
	private WindowApplication app;
	
	private boolean busy = false;
	
	public State(){
		init();
	}
	
	public void init(){
		this.elements = new ArrayList();
		this.script = new Vector();
		this.scripting = true;
		this.fileUpload = null;
		this.url = null;
	}

	public void add(Element e){
		elements.add(e);
		e.setState(this);
	}

	public Element get(String id){
		Iterator i = elements.iterator();
		while(i.hasNext()){
			Element element = (Element)i.next();
			Element found  = element.getElement(id);
			if(found != null){
				return found;
			}
		}
		return null;
	}
	public void addCommand(String cmd) {
		if (scripting) {
			this.script.add(cmd);
		}
	}
	
	public void addCommands(Vector cmdVector){
		Iterator i = cmdVector.iterator();
		while(i.hasNext()){
			String cmd = (String)i.next();
			addCommand(cmd);
		}
	}

	public void clearScript() {
		this.script.clear();
	}

	public Vector getScript() {
		return this.script;
	}

	public void scriptingOff() {
		scripting = false;
	}

	public void scriptingOn() {
		scripting = true;
	}
	public FileUpload getFileUpload() {
		return fileUpload;
	}
	public void setFileUpload(FileUpload fileUpload) {
		this.fileUpload = fileUpload;
	}
	public URL getUrl() {
		return url;
	}
	public void setUrl(URL url) {
		this.url = url;
	}
	
	public void setDebug(boolean b){
		if(b){
			addCommand("debug = true;");
		}
		else{
			addCommand("debug = false;");
		}
		
	}
	
	public synchronized void begin(){
		while(busy){
			try{
				wait();
			}catch (InterruptedException e){}
		}
		busy = true;
	}
	
	public synchronized void end(){
		busy = false;
		notifyAll();
	}

	protected WindowApplication getApp() {
		return app;
	}

	protected void setApp(WindowApplication app) {
		this.app = app;
		this.add(app.initialize());
	}

}
